package com.sx.zongzhi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.MultiImageAdapter;
import com.sx.zongzhi.adapter.SpinnerPubAdapter;
import com.sx.zongzhi.bean.GlobalBean;
import com.sx.zongzhi.bean.KeyPunishDetailBean;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.PhotoBean;
import com.sx.zongzhi.bean.PublicBean;
import com.sx.zongzhi.net.ServiceFactory;
import com.sx.zongzhi.presenter.KeyPunishAddPest;
import com.sx.zongzhi.presenter.PublicListPest;
import com.sx.zongzhi.presenter.UploadFilePest;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.IKeyAreaAddView;
import com.sx.zongzhi.view.IPublicBeanView;
import com.sx.zongzhi.view.UploadFileView;
import com.sx.zongzhi.widget.LoadDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.sx.zongzhi.R.string.submit;


/**
 * 重点地区排查整治编辑/新增
 */
public class KeyPunishEditActivity extends BaseActivity implements IPublicBeanView ,
        IKeyAreaAddView,UploadFileView{

    @BindView(R.id.tv_PunishOrder) EditText et_PunishOrder;
    @BindView(R.id.sp_OrderProblem) Spinner sp_OrderProblem;
    @BindView(R.id.sp_InvolveType) Spinner sp_InvolveType;
    @BindView(R.id.tv_InvolveRange) EditText et_InvolveRange;
    @BindView(R.id.tv_LeaderComp) EditText et_LeaderComp;
    @BindView(R.id.tv_JoinComp) EditText et_JoinComp;
    @BindView(R.id.tv_PunishLeader) EditText et_PunishLeader;
    @BindView(R.id.tv_leaderTel) EditText et_leaderTel;
    @BindView(R.id.tv_LeaderPhone) EditText et_LeaderPhone;
    @BindView(R.id.tv_PunishTime) TextView tv_PunishTime;
    @BindView(R.id.tv_UncoverNum) EditText et_UncoverNum;
    @BindView(R.id.tv_FindNum) EditText et_FindNum;
    @BindView(R.id.tv_PunishState) EditText et_PunishState;
    @BindView(R.id.sp_Evaluate) Spinner sp_Evaluate;
    @BindView(R.id.recyclerView) RecyclerView recyclerView;
    private MultiImageAdapter adapter;
    private List<PhotoBean> selectList = new ArrayList<>();

    private List<GlobalBean> problemList=new ArrayList<>();
    private List<GlobalBean> involveList=new ArrayList<>();
    private List<GlobalBean> evaluateList=new ArrayList<>();
    //区域id
    private String keyPunishId="";
    private String orgId="";
    //详情
    private KeyPunishDetailBean detailBean;
    private KeyPunishAddPest punishAddPest;
    /**修改时删除的图片 id集合*/
    private List<String> removeList;
    /**新增的图片地址*/
    private List<String> upList;
    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_key_punish_edit);
        ButterKnife.bind(this);
        setTitleRight(submit);
        keyPunishId=getIntent().getStringExtra("keyPunishId");
        detailBean= (KeyPunishDetailBean) getIntent().getSerializableExtra("KeyPunishDetailBean");
        orgId= getIntent().getStringExtra("orgId");
        initView();
        initData();
    }

    private void initData() {
        punishAddPest=new KeyPunishAddPest(this);
        PublicListPest publicListPest=new PublicListPest(this);
        publicListPest.getPublicList("涉及区域类型");
        publicListPest.getPublicList("突出治安问题");
        publicListPest.getPublicList("效果评估");
    }

    private void initView() {
        if (detailBean!=null&&detailBean.getFiles()!=null&&detailBean.getFiles().size()>0){
            selectList.clear();
            for (PhotoBean photoBean:detailBean.getFiles()){
                photoBean.setPath(ServiceFactory.NEW_API_BASE_URL + File.separator + photoBean.getPath());
                selectList.add(photoBean);
            }
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
        adapter = new MultiImageAdapter(this, mAddPicClickListener);
        adapter.setList(selectList);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new MultiImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(final int position, View v) {
                String path = selectList.get(position).getPath();
                startActivity(new Intent(KeyPunishEditActivity.this, ImagePlayActivity.class).putExtra(
                            "path", path));

            }
        });
        adapter.setOnDeleteNetFileClickListener(new MultiImageAdapter.OnDeleteNetFileClickListener() {
            @Override
            public void deleteFileId(String fileId) {//只有网络图片会走
                if (removeList==null){
                    removeList=new ArrayList<String>();
                }
                removeList.add(fileId);
            }
        });

        if (detailBean!=null){//修改
            setTitleName(R.string.punish_edit);
            et_PunishOrder.setText(detailBean.getSecurityKeyAreas());
            et_InvolveRange.setText(detailBean.getRelateArea());
            et_LeaderComp.setText(detailBean.getRepairLeaderUnit());
            et_JoinComp.setText(detailBean.getRepairPartakeUnit());
            et_PunishLeader.setText(detailBean.getLeaderUnitDirector());
            et_leaderTel.setText(detailBean.getLeaderUnitDirectorTelephone());
            et_LeaderPhone.setText(detailBean.getLeaderUnitDirectorMobileNumber());
            tv_PunishTime.setText(detailBean.getRepairTimelimit());
            et_UncoverNum.setText(detailBean.getInvestigatePunishNumber()+"");
            et_FindNum.setText(detailBean.getSolveNumber()+"");
            et_PunishState.setText(detailBean.getRepairSituation());
        }else {
            setTitleName(R.string.punish_add);
        }
    }



    @OnClick({R.id.tv_right,R.id.tv_PunishTime})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.tv_right://提交
                submit();
                break;
            case R.id.tv_PunishTime:
                BaseUtil.createDataPop(this,tv_PunishTime);
                break;

        }
    }

    private void submit() {
        String punish=et_PunishOrder.getText().toString().trim();
        if (BaseUtil.isEmpty(punish)){
            et_PunishOrder.setError("不能为空");
            return;
        }
        if (punish.length() > 50){
            et_PunishOrder.setError("长度不能大于50个字符");
            return;
        }
        if(problemList.size()<1){
            ToastUtils.showToast(this,"请选择治安突出问题");
            return;
        }
        if(involveList.size()<1){
            ToastUtils.showToast(this,"请选择涉及区域类型");
            return;
        }
        String involveRange=et_InvolveRange.getText().toString().trim();
        if (BaseUtil.isEmpty(involveRange)){
            et_InvolveRange.setError("不能为空");
            return;
        }
        if (involveRange.length() > 200){
            et_InvolveRange.setError("长度不能大于200个字符");
            return;
        }
        if (et_LeaderComp.getText().toString().trim().length() > 50){
            et_LeaderComp.setError("长度不能大于50个字符");
            return;
        }
        if (et_JoinComp.getText().toString().trim().length() > 200){
            et_JoinComp.setError("长度不能大于200个字符");
            return;
        }
        String leader=et_PunishLeader.getText().toString().trim();
        if (BaseUtil.isEmpty(leader)){
            et_PunishLeader.setError("不能为空");
            return;
        }
        if (leader.length() > 20 || leader.length() < 2){
            et_PunishLeader.setError("不能小于2或大于20个字符");
            return;
        }
        String tel=et_leaderTel.getText().toString().trim();
        String phone=et_LeaderPhone.getText().toString().trim();
        if (BaseUtil.isEmpty(tel)&&BaseUtil.isEmpty(phone)){
            et_LeaderPhone.setError("至少输入一种联系方式");
            return;
        }
        if (!BaseUtil.isEmpty(phone)&&!BaseUtil.isMobile(phone)){
            et_LeaderPhone.setError("请输入正确手机号");
            return;
        }
        String time=tv_PunishTime.getText().toString().trim();
        if (BaseUtil.isEmpty(time)){
            ToastUtils.showToast(this,"请选择时限");
            return;
        }
        int num = Integer.valueOf(et_UncoverNum.getText().toString().trim());
        if (num < 0 || num > 999999){
            et_UncoverNum.setError("只能输入正整数且不能大于999999");
            return;
        }
        int num1 = Integer.valueOf(et_FindNum.getText().toString().trim());
        if (num1 < 0 || num1 > 999999){
            et_FindNum.setError("只能输入正整数且不能大于999999");
            return;
        }
        String state=et_PunishState.getText().toString().trim();
        if (BaseUtil.isEmpty(state)){
            et_PunishState.setError("不能为空");
            return;
        }
        if (state.length() > 300){
            et_PunishState.setError("长度不能大于300个字符");
            return;
        }
        if(evaluateList.size()<1){
            ToastUtils.showToast(this,"请选择效果评估");
            return;
        }
        LoadDialog.show(this,"检测同名");
        //判断有没有相同的名称
        punishAddPest.AddKeyPunish("hasSocialSecurity.action",orgId,punish,
                    BaseUtil.isEmpty(keyPunishId)?"":keyPunishId);
    }

    private void submitDone() {
        if (detailBean==null){
            detailBean=new KeyPunishDetailBean();
        }
        detailBean.setSecurityKeyAreas(et_PunishOrder.getText().toString().trim());
        GlobalBean pBean=(GlobalBean)sp_OrderProblem.getSelectedItem();
        if (pBean!=null){
            GlobalBean spBean=new GlobalBean();
            spBean.setId(pBean.getId());
            detailBean.setSecurityProblems(spBean);
        }
        GlobalBean iBean=(GlobalBean)sp_InvolveType.getSelectedItem();
        if (iBean!=null){
            GlobalBean iTBean=new GlobalBean();
            iTBean.setId(iBean.getId());
            detailBean.setInvolvedType(iTBean);
        }
        detailBean.setRelateArea(et_InvolveRange.getText().toString().trim());
        detailBean.setRepairLeaderUnit(et_LeaderComp.getText().toString().trim());
        detailBean.setRepairPartakeUnit(et_JoinComp.getText().toString().trim());
        detailBean.setLeaderUnitDirector(et_PunishLeader.getText().toString().trim());
        detailBean.setLeaderUnitDirectorTelephone(et_leaderTel.getText().toString().trim());
        detailBean.setLeaderUnitDirectorMobileNumber(et_LeaderPhone.getText().toString().trim());
        detailBean.setRepairTimelimit(tv_PunishTime.getText().toString().trim());
        String uncoverNum=et_UncoverNum.getText().toString().trim();
        detailBean.setInvestigatePunishNumber(BaseUtil.isEmpty(uncoverNum)?0:Integer.parseInt(uncoverNum));
        String findNum=et_FindNum.getText().toString().trim();
        detailBean.setSolveNumber(BaseUtil.isEmpty(findNum)?0:Integer.parseInt(findNum));
        detailBean.setRepairSituation(et_PunishState.getText().toString().trim());
        GlobalBean eBean=(GlobalBean)sp_Evaluate.getSelectedItem();
        if (eBean!=null){
            KeyPunishDetailBean.EffectEvaluateBean eeBean=new KeyPunishDetailBean.EffectEvaluateBean();
            eeBean.setId(eBean.getId());
            detailBean.setEffectEvaluate(eeBean);
        }
        LoadDialog.show(this,"正在提交");
        if (BaseUtil.isEmpty(keyPunishId)){//新增
            punishAddPest.AddKeyPunish("addSocialSecurity.action","",orgId,detailBean,upList,removeList);
        }else {//编辑
            punishAddPest.AddKeyPunish("updateSocialSecurity.action",keyPunishId,orgId,detailBean,upList,removeList);
        }
    }



    //点击的添加文件的响应
    private MultiImageAdapter.AddPicClickListener mAddPicClickListener =
            new MultiImageAdapter.AddPicClickListener() {
        @Override
        public void onAddPicClick() {
            int max = 3 - selectList.size();
            if (max > 0) {
                PictureSelector.create(KeyPunishEditActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.MULTIPLE)
                        .maxSelectNum(max)// 最大图片选择数量 int
                        .previewImage(true)// 是否可预览图片
                        .enableCrop(true)
                        .compress(true)
                        .compressGrade(Luban.CUSTOM_GEAR)
                        .compressMaxKB(200)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            } else {
                ToastUtils.showToast(KeyPunishEditActivity.this, "最多上传三项");
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST://选图片
                    List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                    if (!picUrls.isEmpty()) {
                        for (LocalMedia localMedia : picUrls) {
                            String path = localMedia.getCompressPath();
                            String type = path.substring(path.lastIndexOf("."));
                            selectList.add(new PhotoBean(path, type));
                        }
                        if (adapter != null) adapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    }


    @Override
    public void showError(String message) {
        LoadDialog.dismiss(this);
        ToastUtils.showToast(this,message);
    }


    @Override
    public void getPublicList(PublicBean publicBean) {
        if ("效果评估".equals(publicBean.getDomainName())){
            evaluateList=publicBean.getDicts();
            if (evaluateList!=null){
                SpinnerPubAdapter adapter=new SpinnerPubAdapter(this,R.layout.item_text,evaluateList);
                sp_Evaluate.setAdapter(adapter);
                if (detailBean!=null){
                    showEvaluate();
                }
            }
        }
        if ("涉及区域类型".equals(publicBean.getDomainName())){
            involveList=publicBean.getDicts();
            if (involveList!=null){
                SpinnerPubAdapter adapter=new SpinnerPubAdapter(this,R.layout.item_text,involveList);
                sp_InvolveType.setAdapter(adapter);
                if (detailBean!=null){
                    showType();
                }
            }
        }
        if ("突出治安问题".equals(publicBean.getDomainName())){
            problemList=publicBean.getDicts();
            if (problemList!=null){
                SpinnerPubAdapter adapter=new SpinnerPubAdapter(this,R.layout.item_text,problemList);
                sp_OrderProblem.setAdapter(adapter);
                if (detailBean!=null){
                    showProblem();
                }
            }
        }
    }
    private void showEvaluate() {
        if (detailBean.getEffectEvaluate()!=null) {
            for (int i = 0; i < evaluateList.size(); i++) {
                if (evaluateList.get(i).getId().equals(detailBean.getEffectEvaluate().getId())) {
                        sp_Evaluate.setSelection(i);
                }
            }
        }

    }
    private void showProblem() {
        if (detailBean.getInvolvedType()!=null) {
            for (int i = 0; i < problemList.size(); i++) {
                if (problemList.get(i).getId().equals(detailBean.getSecurityProblems().getId())) {
                    sp_OrderProblem.setSelection(i);
                }
            }
        }
    }
    private void showType() {
        if (detailBean.getInvolvedType()!=null){
            for (int i=0;i<involveList.size();i++){
                if (involveList.get(i).getId().equals( detailBean.getInvolvedType().getId())){
                    sp_InvolveType.setSelection(i);
                }
            }

        }
    }


    @Override
    public void uploadSuccess(List<PhotoBean> beans) {
      if (beans!=null&&beans.size()>0){
          if (upList==null){
              upList=new ArrayList<>();
          }
          for (PhotoBean photoBean:beans){
              upList.add(photoBean.getPath());
          }
          submitDone();
      }else {
          LoadDialog.dismiss(this);
          ToastUtils.showToast(this,"文件上传异常");
      }
    }

    @Override
    public void addSuccess(Boolean result) {
        LoadDialog.dismiss(this);
        if (result){
            ToastUtils.showToast(this,"提交成功");
            MyRxBus.get().post(new MsgEvent("KeyPunishActivity",1,"提交成功"));
            finish();
        }else {
            ToastUtils.showToast(this,"提交失败");
        }

    }

    @Override
    public void nameSuccess(Boolean result) {
        if (!result){
            if (selectList.size()>0){
                List<File> files = new ArrayList<>();
                for (PhotoBean photoBean:selectList){
                    if (!photoBean.getPath().startsWith("http://")){
                        files.add(new File(photoBean.getPath()));
                    }
                }
                if (files.size()>0){
                    LoadDialog.show(this,"正在上传文件...");
                    new UploadFilePest(this).uploadFile(this,files);
                }else {
                    submitDone();
                }
            }else {
                submitDone();
            }

        }else {
            LoadDialog.dismiss(this);
            ToastUtils.showToast(this,"该地区已存在，请更改治安重点地区");
        }
    }
}
